package num;

import java.util.HashMap;
import java.util.Map;

/**
 * @author pengfei.hpf
 * @date 2020/3/31
 * @verdion 1.0.0
 * 166. 分数到小数
 * 给定两个整数，分别表示分数的分子 numerator 和分母 denominator，以字符串形式返回小数。
 *
 * 如果小数部分为循环小数，则将循环的部分括在括号内。
 *
 * 示例 1:
 *
 * 输入: numerator = 1, denominator = 2
 * 输出: "0.5"
 * 示例 2:
 *
 * 输入: numerator = 2, denominator = 1
 * 输出: "2"
 * 示例 3:
 *
 * 输入: numerator = 2, denominator = 3
 * 输出: "0.(6)"
 */
public class FractionToDecimal {
    public String fractionToDecimal(int numerator, int denominator) {
        if(denominator == 0){
            return "";
        }
        if(numerator == 0){
            return "0";
        }
        StringBuilder builder = new StringBuilder();
        if(numerator >0 ^ denominator > 0){
            builder.append("-");
        }
        long num = Math.abs((long) numerator);
        long den = Math.abs((long) denominator);
        builder.append(num / den);
        num %= den;
        if(num > 0){
            builder.append(".");
        }
        Map<Long, Integer> map = new HashMap<>();
        int index = builder.length();
        while(num > 0){
            if(map.containsKey(num)){
                builder.insert(map.get(num), "(");
                builder.append(")");
                break;
            }
            map.put(num, index);
            num *= 10;
            builder.append(num / den);
            num %= den;
            index ++;
        }
        return builder.toString();
    }
}
